package com.zhouxiaoge.socket.serversocket;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/***************************************************
 *                    _ooOoo_                  *   
 *                   o8888888o                 * 佛        
 *                  88'' . ''88                * 祖 
 *                  ( | -_- | )                * 保 
 *                   0\  =  /0                 * 佑 
 *                ____/'---'\____              *    
 *              .'  \\|     |//  '.            * 永 
 *             /  \\|||  :  |||//  \           * 无 
 *            /  _||||| -:- |||||-  \          * BUG
 *            |   | \\\  -  /// |   |          *
 *            | \_|  ''\---/''  |   |          * 阿
 *            \  .-\__  `-`  ___/-. /          * 弥
 *          ___`. .'  /--.--\  `. . __         * 陀
 *       ."" '<  ‘.___\_<|>_/___.’  >'"".      * 佛
 *      | | :  ` - `.;`\ _ /`;.`/ - ` : | |    *
 *      \  \ `-.   \_ __\ /__ _/   .-` /  /    * 
 * ======`-.____`-.___\_____/___.-`____.-'=====*
 * @author 周明阳 mail:gqzmy@outlook.com 时间:2017-12-11 9:23
 */
public class SocketThread extends Thread {
    private ServerSocket serverSocket = null;

    public SocketThread(ServerSocket serverScoket) {
        try {
            if (null == serverSocket) {
                this.serverSocket = new ServerSocket(8888);
                System.out.println("=========================ServerSocket Start=============================");
            }
        } catch (Exception e) {
            System.out.println("SocketThread创建socket服务出错");
            e.printStackTrace();
        }

    }

    @Override
    public void run() {
        while (!this.isInterrupted()) {
            try {
                Socket socket = serverSocket.accept();
                if (null != socket && !socket.isClosed()) {
                    //处理接受的数据
                    new SocketOperate(socket).start();
                }
                socket.setSoTimeout(30000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void closeSocketServer() {
        try {
            if (null != serverSocket && !serverSocket.isClosed()) {
                serverSocket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
